//
//  CommunityViewController.m
//  aMoment
//
//  Created by dllo on 15/9/30.
//  Copyright © 2015年 LuckyHan. All rights reserved.
//

#import "CommunityViewController.h"
#import "AllHeaderFiles.h"

@interface CommunityViewController ()<UITableViewDataSource, UITableViewDelegate, ImageViewTagDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, assign)NSInteger start;
@property(nonatomic, retain)UIView *rightBarButtonView;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, retain)NSArray *itemArray;
@property(nonatomic, assign)NSInteger itemFlag;
@property(nonatomic, retain)UISegmentedControl *segmentedControl;
@property(nonatomic, assign)NSInteger segmentFlag;
@property(nonatomic, retain)MBProgressHUD *progressView;
@property(nonatomic, retain)NSArray *listArray;
@end

@implementation CommunityViewController

- (void)dealloc
{
    [_tableView release];
    [_rightBarButtonView release];
    [_segmentedControl release];
    [_progressView release];
    [_listArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"社区";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"话题" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarButtonAction)];
    self.dataSourceArray = [NSMutableArray array];
    [self getData];
    
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _start = 0;
        [self getData];
    }];
//    [_tableView.header beginRefreshing];
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _start += 10;
        [self getData];
    }];
}

#pragma mark 获取数据
- (void)getData
{
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"话题"]) {
        self.urlString = URLSTRING_COMMUNITY_TOPIC;
    } else {
        self.urlString = URLSTRING_COMMUNITY_GROUP;
    }
    if (!_segmentedControl.selectedSegmentIndex) {
        self.bodyString = BODYSTRING_COMMUNITY_HOT;
    } else {
        self.bodyString = BODYSTRING_COMMUNITY_NEW;
    }
//    NSString *bodyString = [NSString stringWithFormat:@"start=%ld&limit=10&client=2&sort=hot", _start];
    [NetworkRequest getDataWithURLString:self.urlString BodyString:self.bodyString DataBlock:^(id data) {
        //移除加载中提示视图
        [_progressView removeFromSuperview];
        
        if (!_start) {
            [self.dataSourceArray removeAllObjects];
        }
        self.listArray = [[(NSDictionary *)data objectForKey:@"data"] objectForKey:@"list"];
        for (NSDictionary *dict in _listArray) {
            Community *community = [[Community alloc] init];
            [community setValuesForKeysWithDictionary:dict];
            [self.dataSourceArray addObject:community];
        }
        [_tableView reloadData];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }];
}

#pragma mark 点击话题按钮方法
- (void)clickRightBarButtonAction
{
    if (!_flag) {
//        _rightBarButtonView.hidden = NO;
        self.navigationItem.rightBarButtonItem.title = @"小组";
        _flag = 1;
    } else {
//        _rightBarButtonView.hidden = YES;
        self.navigationItem.rightBarButtonItem.title = @"话题";
        _flag = 0;
    }
    _segmentedControl.selectedSegmentIndex = 0;
//    NSLog(@"%ld", (long)_segmentedControl.selectedSegmentIndex);
    [_tableView.header beginRefreshing];
}

#pragma mark 点击segment方法
- (void)segmentAction:(UISegmentedControl *)segment
{
//    if (!segment.selectedSegmentIndex) {
//        _segmentFlag = 0;
//    } else {
//        _segmentFlag = 1;
//    }
    [_tableView.header beginRefreshing];
}

//#pragma mark 点击话题子视图方法
//- (void)changeItemWithLabel:(UITapGestureRecognizer *)tap
//{
//    if (tap.view.tag == 1000) {
//        NSLog(@"1000");
//    } else {
//        NSLog(@"1001");
//    }
//    [self clickRightBarButtonAction];
//    self.navigationItem.rightBarButtonItem.title = _itemArray[tap.view.tag - 1000];
//    [_tableView.header beginRefreshing];
//}

- (void)loadView
{
    [super loadView];
    //创建头视图
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"最热", @"最新"]];
    _segmentedControl.selectedSegmentIndex = 0;
    [_segmentedControl setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil] forState:UIControlStateNormal];
    _segmentedControl.frame = CGRectMake(0, 0, 170 * FIT_WIDTH, 30);
    [_segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = _segmentedControl;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.Width, self.view.Height - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    
    //创建话题视图
//    [self createRightBarButtonView];
    
    //创建加载中提示视图
    self.progressView = [LoadingProgress createViewWithSuperviewFrame:self.view.frame];
    [self.view addSubview:_progressView];
    [_progressView release];
}

//#pragma mark 创建话题视图
//- (void)createRightBarButtonView
//{
//    //创建话题视图
//    self.itemArray = [NSArray arrayWithObjects:@"话题", @"小组", nil];
//    _rightBarButtonView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 70 * FIT_WIDTH, 0, 70 * FIT_WIDTH, 50 * FIT_HEIGHT)];
//    _rightBarButtonView.backgroundColor = [UIColor blackColor];
//    _rightBarButtonView.hidden = YES;
//    for (NSInteger i = 0; i < 2; i++) {
//        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, i * _rightBarButtonView.Height / 2, _rightBarButtonView.Width, _rightBarButtonView.Height / 2)];
//        label.text = [NSString stringWithFormat:@" %@", _itemArray[i]];
//        label.textColor = [UIColor whiteColor];
//        label.font = [UIFont systemFontOfSize:FONTSIZE_MIDDLE];
//        label.userInteractionEnabled = YES;
//        label.tag = 1000 + i;
//        [_rightBarButtonView addSubview:label];
//        [label release];
//    }
//    [self.view addSubview:_rightBarButtonView];
//    [_rightBarButtonView release];
//    //给话题视图的子视图添加手势
//    for (NSInteger i = 0; i < _itemArray.count; i++) {
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeItemWithLabel:)];
//        [_rightBarButtonView.subviews[i] addGestureRecognizer:tap];
//        [tap release];
//    }
//}

#pragma mark cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArray.count;
}

#pragma mark cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //话题样式
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"话题"]) {
        //有图片
        if (![[self.dataSourceArray[indexPath.row] coverimg] isEqualToString:@""] || ![[self.dataSourceArray[indexPath.row] songid] isEqualToString:@""]/* || (![[self.dataSourceArray[indexPath.row] coverimg] isEqualToString:@""] && ![[self.dataSourceArray[indexPath.row] songid] isEqualToString:@""])*/) {
            static NSString *identifier = @"cell";
            CommunityTableCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[CommunityTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.community = self.dataSourceArray[indexPath.row];
            return cell;
        }
        //无图片
        static NSString *identifier = @"text";
        CommunityTableCellOfText *textCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!textCell) {
            textCell = [[CommunityTableCellOfText alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        textCell.selectionStyle = UITableViewCellSelectionStyleNone;
        textCell.community = self.dataSourceArray[indexPath.row];
        return textCell;
    }
    
    //小组样式
    static NSString *identifier = @"group";
    CommunityTableCellOfGroup *groupCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!groupCell) {
        groupCell = [[CommunityTableCellOfGroup alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    groupCell.delegate = self;
    groupCell.cellTag = 1000 + indexPath.row;
    groupCell.selectionStyle = UITableViewCellSelectionStyleNone;
    groupCell.community = self.dataSourceArray[indexPath.row];
    return groupCell;
}

#pragma mark cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"话题"]) {
        if (![[self.dataSourceArray[indexPath.row] coverimg] isEqualToString:@""] || ![[self.dataSourceArray[indexPath.row] songid] isEqualToString:@""] || (![[self.dataSourceArray[indexPath.row] coverimg] isEqualToString:@""] && ![[self.dataSourceArray[indexPath.row] songid] isEqualToString:@""])) {
            return 100 * FIT_HEIGHT + 85 * FIT_WIDTH;
        }
        return [self getStringHeightWithString:[self.dataSourceArray[indexPath.row] content] LabelWidth:SCREEN_WIDTH - 40 * FIT_WIDTH] + 100 * FIT_HEIGHT;
    }
    return 80 * FIT_HEIGHT + (45 + 80) * FIT_WIDTH;
}

#pragma mark 获取字符串高度
- (CGFloat)getStringHeightWithString:(NSString *)string
                          LabelWidth:(CGFloat)labelWidth
{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil];
    CGRect rect = [string boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    return rect.size.height + 1;
}

#pragma mark cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"%ld", indexPath.row);
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"话题"]) {
        StoreDetailsViewController *detailsVC = [[StoreDetailsViewController alloc] init];
        [self.navigationController pushViewController:detailsVC animated:YES];
        detailsVC.contentID = [self.dataSourceArray[indexPath.row] contentid];
        [detailsVC release];
    }
}

#pragma mark 点击小组图片方法
- (void)passImageViewTag:(NSInteger)tag CellTag:(NSInteger)cellTag
{
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"小组"]) {
//        NSLog(@"%@", self.navigationItem.rightBarButtonItem.title);
        StoreDetailsViewController *detailsVC = [[StoreDetailsViewController alloc] init];
        Community *community = self.dataSourceArray[cellTag - 1000];
        detailsVC.contentID = [community.latestposts[tag - 1000] objectForKey:@"contentid"];
        [self.navigationController pushViewController:detailsVC animated:YES];
        [detailsVC release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
